package com.service.bracelet.export;

import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import com.service.bracelet.util.UtilConsts;

/**
 * 导出数据到excel中，导出格式为xlsx
 * 
 * @author 郭波
 *
 */
public class ExportDataToExcel implements Closeable {

	private SXSSFWorkbook workbook;

	public ExportDataToExcel() {
		this.workbook = new SXSSFWorkbook(100);
	}

	static {
		System.setProperty("java.awt.headless", "true");
	}

	public void exportData(String sheeName, String[] columns, List<Object[]> datas, boolean isInt) {
		int count = columns != null ? columns.length : datas != null && datas.size() > 0 ? datas.get(0).length : 0;
		if (count == 0) {
			return;
		}
		SXSSFSheet sheet = workbook.createSheet(sheeName);
		sheet.setDefaultColumnWidth(count);

		// 标题写入
		int headRow = columns != null ? 1 : 0;
		if (columns != null && columns.length > 0) {
			SXSSFRow row = sheet.createRow(0);
			for (int i = 0, n = columns.length; i < n; i++) {
				SXSSFCell cell = row.createCell(i);
				String headName = columns[i];
				cell.setCellValue(headName); // 写入列名
			}
		}

		// 数据写入
		if (datas != null && datas.size() > 0) {
			for (int i = 0, n = datas.size(); i < n; i++) {
				Object[] data = datas.get(i);
				SXSSFRow r = sheet.createRow(i + headRow);
				for (int j = 0, m = data.length; j < m; j++) {
					Object v = data[j];
					if (v != null) {
						SXSSFCell cell = r.createCell(j);
						if (j >= UtilConsts.STR_COLUMN) {
							cell.setCellValue(isInt ? (int) v : (double) v);
						} else {
							cell.setCellValue((String) v);
						}
					}
				}
			}
		}
	}

	/**
	 * 输出数据到输出流中
	 * 
	 * @param out
	 * @throws IOException
	 */
	public void write(OutputStream out) throws IOException {
		if (out == null) {
			return;
		}
		this.workbook.write(out);
		out.flush();
	}

	@Override
	public void close() throws IOException {
		this.workbook.dispose();
	}
}
